package best.driver.android;

import android.app.*;
import android.content.*;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import best.driver.android.Activity.Base.BaseActivity;
import best.driver.android.Activity.Order.AcceptOrderActivity;
import best.driver.android.Activity.Order.OrderOperationActivity;
import best.driver.android.AppConfig;
import best.driver.android.Beans.AppVersionInfo;
import best.driver.android.Beans.NewOrderInfo;
import best.driver.android.Beans.OrderDetailInfo;
import best.driver.android.Beans.PushType;
import best.driver.android.Event.DownloadApkEvent;
import best.driver.android.Event.NewOrderCanceledEvent;
import best.driver.android.HomeActivity;
import best.driver.android.Map.location.LastKnowLocation;
import best.driver.android.Map.location.LocationManager;
import best.driver.android.Model.BestDataBaseHelper;
import best.driver.android.Model.DriverPositionModel;
import best.driver.android.Model.OrderDetailModel;
import best.driver.android.NetBase.BackService;
import best.driver.android.R;
import best.driver.android.Utils.*;
import best.driver.android.common.app.AppProxy;
import best.driver.android.common.network.ApiObjectRequest;
import best.driver.android.common.utils.DeviceUtils;
import best.driver.android.manager.OrderManager;
import best.driver.android.manager.UpgradeManager;
import com.activeandroid.ActiveAndroid;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
//import com.baidu.mapapi.BMapManager;
//import com.baidu.mapapi.MKGeneralListener;
//import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import best.driver.android.common.app.AppProxyFactory;
import best.driver.android.common.network.ApiJsonRequest;
import best.driver.android.common.network.ApiRequest;
import best.driver.android.common.network.BestError;
import best.driver.android.manager.UserInfoManager;
import de.greenrobot.event.EventBus;
import org.json.JSONObject;

import java.util.*;

public class BestApp extends Application {

    public LastKnowLocation lastKnowLocation = new LastKnowLocation();

    public static String mWorkStatus;

    private List<Activity> mList = new LinkedList<Activity>();
    private AlarmManager am = null;
    private static BestApp instance;
    public static Handler handler = new Handler();
    private boolean initialized = false;

    private Timer mTimer;
    private TimerTask mTimerTask;

    private IntentFilter mIntentFilter;
    private Intent mServiceIntent;
    private LocalBroadcastManager mLocalBroadcastManager;
    public BroadcastReceiver mReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BackService.PUSH_MESSAGE_ACTION)) {
                try {
                    byte type = intent.getByteExtra("type", (byte) 0);
                    int length = intent.getIntExtra("length", 0);
                    final String content = intent.getStringExtra("content");
                    if (length > 0 && !TextUtils.isEmpty(content) && type == PushType.NEW_ORDER) {
                        getNewOrder(content, type);
                    } else if (length > 0 && !TextUtils.isEmpty(content) && type == PushType.NEW_ORDER_ACCEPTED) {
                        getNewOrder(content, type);
                    } else if (length > 0 && !TextUtils.isEmpty(content) && type == PushType.UPLOAD_POSITION) {
                        String positions[] = content.split(",");
                        if(positions.length > 1) {
                            for (int i = 1; i < positions.length; i++) {
                                BestDataBaseHelper.getInstance().deletePosition(Long.valueOf(positions[i]));
                            }
                        }
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                uploadPosition();
                            }
                        }, 2000);

                    } else if (length > 0 && !TextUtils.isEmpty(content) && type == PushType.NEW_ORDER_FAILED) {
                        showNewOrderFail(content, type);
                    } else if (length > 0 && !TextUtils.isEmpty(content) && type == PushType.NEW_ORDER_CANCELED) {
                        showNewOrderCanceled(content, type);
                        OrderManager.getInstance().deleteCurrentOrder(content);
                    }
                } catch (Exception e) {
                    Log.d("exception", e.getMessage());
                    e.printStackTrace();
                }
            } else if (action.equals(AppConstant.BROADCAST_ACTION_PROGRESS)) {
                int percent = intent.getIntExtra(AppConstant.EXTRA_progress, 0);
//                Logger.d("percent_app", percent+"");
                DownloadApkEvent event = new DownloadApkEvent();
                event.process = percent;
                EventBus.getDefault().post(event);
            }
            Logger.d(action, action);

        }
    };

    private void getNewOrder(final String orderId, final byte status) {
        String locationString = lastKnowLocation.mLng + "," + lastKnowLocation.mLat;
        ApiObjectRequest<NewOrderInfo> request = RequestFactory.createGetNewOrderInfoRequest(orderId, locationString);
        request.setListener(new ApiRequest.ApiRequestListener<NewOrderInfo>() {
            @Override
            public void onRequestSuccess(NewOrderInfo response) {
                if(getLastActivity() instanceof AcceptOrderActivity) {
                    ((AcceptOrderActivity) getLastActivity()).showOrderNew(response, status);
                    return;
                }
                Intent acceptIntent = new Intent(BestApp.getInstance().getApplicationContext(), AcceptOrderActivity.class);
                acceptIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                acceptIntent.putExtra("orderId", orderId);
                acceptIntent.putExtra("new_order", response);
                acceptIntent.putExtra("status", status);
                startActivity(acceptIntent);
            }

            @Override
            public void onRequestError(BestError error) {
                int a = 5;
            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);

    }

    private void showNewOrderFail(String orderId, byte type) {
        if(getLastActivity() instanceof AcceptOrderActivity) {
            ((AcceptOrderActivity) getLastActivity()).showOrderAcceptFailed(orderId);
            return;
        }
    }

    private void showNewOrderCanceled(String orderId, byte type) {
        if(getLastActivity() instanceof AcceptOrderActivity) {
            ((AcceptOrderActivity) getLastActivity()).showOrderAcceptCanceled(orderId);
            return;
        } else if(getLastActivity() instanceof OrderOperationActivity) {
            NewOrderCanceledEvent event = new NewOrderCanceledEvent();
            event.orderId = orderId;
            EventBus.getDefault().post(event);
        }
    }

    private void getOrderDetail(final String orderId, final byte type) {
        ApiObjectRequest<OrderDetailInfo> request = RequestFactory.createGetOrderDetailInfoRequest(orderId);
        request.setListener(new ApiRequest.ApiRequestListener<OrderDetailInfo>() {
            @Override
            public void onRequestSuccess(OrderDetailInfo response) {
                if(getLastActivity() instanceof AcceptOrderActivity) {
                    ((AcceptOrderActivity) getLastActivity()).showOrderNew(response, type);
                    return;
                }
                Intent acceptIntent = new Intent(BestApp.getInstance().getApplicationContext(), AcceptOrderActivity.class);
                acceptIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                acceptIntent.putExtra("orderId", orderId);
                acceptIntent.putExtra("orderDetail", response);
                acceptIntent.putExtra("status", type);
                startActivity(acceptIntent);
            }

            @Override
            public void onRequestError(BestError error) {

            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    public static DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.icon_app)
            .showImageForEmptyUri(R.drawable.icon_app)
            .showImageOnFail(R.drawable.icon_app)
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .build();

    public static BestApp getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        instance = this;
        super.onCreate();
        String process = getCurProcessName(this);
        if (!process.equals("best.driver.android")) {
            Logger.d("process", process);
            return;
        }
        AppConfig.loadContextMode();
        registerForgroudReceiver();

        initApp();
        AppProxyFactory.registerProxy(getApplicationContext(),
                CustomerAppProxy.class);
        LocationManager.getInstance().init();
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(BackService.HEART_BEAT_ACTION);
        mIntentFilter.addAction(BackService.MESSAGE_ACTION);
        mIntentFilter.addAction(BackService.PUSH_MESSAGE_ACTION);
        mIntentFilter.addAction(AppConstant.BROADCAST_ACTION_PROGRESS);
        mServiceIntent = new Intent(this, BackService.class);
        registerReceiver(mReciver, mIntentFilter);
        startService(new Intent(this, BackService.class));
        //getVersionRequest();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
                UpgradeManager.getInstance(BestApp.getInstance()).checkAndNotify(BestApp.getInstance());
//            }
//        }, 10000);

    }

    public synchronized void initApp() {
        if (!initialized) {
            initialized = true;
            ActiveAndroid.initialize(this);
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                    getApplicationContext()).threadPriority(Thread.NORM_PRIORITY)// 加载图片的线程数
                    .denyCacheImageMultipleSizesInMemory() // 解码图像的大尺寸将在内存中缓存先前解码图像的小尺寸。
                    .tasksProcessingOrder(QueueProcessingType.LIFO)// 设置加载显示图片队列进程
                    .build();
            ImageLoader.getInstance().init(config);

            initBMap();

            //LocationManager.requestLoc();


        }

    }

    public void initBMap() {
        SDKInitializer.initialize(getApplicationContext());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LocationManager.getInstance().requestLoc(5000);
            }
        }, 6000);
        startTimer(60000);

    }

//    public BMapManager getBMapMan() {
//        return mBMapMan;
//    }

    public void exit() {
        finishAllActivities();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    public void onTerminate() {
        //LocationManager.stopLocService();
        super.onTerminate();
        mLocalBroadcastManager.unregisterReceiver(mReciver);
        ActiveAndroid.dispose();
        exit();

    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }

    // add Activity
    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    public void removeActivity(Activity activity) {
        mList.remove(activity);
    }

    public Activity getLastActivity() {
        if (mList.size() == 0) {
            return null;
        }
        return mList.get(mList.size() - 1);
    }

    public void finishAllActivities() {
        try {
            for (Activity activity : mList) {
                if (activity != null) {
                    activity.finish();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mList.clear();
    }

    // 切前台的通知
    private BroadcastReceiver forgroudReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        }
    };


    private void registerForgroudReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BackgroundUtils.APP_ENTER_FOREGROUND_BROADCAST);
        registerReceiver(forgroudReceiver, filter);
    }

    String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {

                return appProcess.processName;
            }
        }
        return null;
    }

    public void sendMessage(String msg) {
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public void uploadPosition() {
//        if(true){
//            List<DriverPositionModel> models = new Select().from(DriverPositionModel.class).execute();
//            if(models.size() > 0) {
//                long time = models.get(0).timeStamp;
//                new Delete().from(DriverPositionModel.class).where("time_stamp = ?", time).execute();
//                List<DriverPositionModel> positionModels = BestDataBaseHelper.getInstance().getDriverPositionModels();
//                Logger.d("MessageTruehhh", positionModels.size() + " " + positionModels.get(0).timeStamp);
//            }
//
//            return;
//        }
        if(!UserInfoManager.getInstance().isCheckSucceed() || !UserInfoManager.getInstance().isLogin() || !UserInfoManager.getInstance().getAcceptOrderStatus()) {
            return;
        }

        List<DriverPositionModel> positionModels = BestDataBaseHelper.getInstance().getDriverPositionModels();
        if(positionModels == null || positionModels.size() == 0) {
            return;
        }
        if(positionModels!= null && positionModels.size() > 10) {
            int size = positionModels.size();
            positionModels = positionModels.subList(0, 10);
        }
        String uploadContent = BestDataBaseHelper.getInstance().convertToString(positionModels);
        Intent intent = new Intent();
        intent.putExtra("message", uploadContent);
        intent.setAction(BackService.MESSAGE_ACTION);
        BestApp.getInstance().sendBroadcast(intent);
    }

    public void uploadPosition(DriverPositionModel model) {
        if(!UserInfoManager.getInstance().isCheckSucceed() || !UserInfoManager.getInstance().isLogin() || !UserInfoManager.getInstance().getAcceptOrderStatus()) {
            return;
        }

        if(OrderManager.getInstance().getCurrentOrder() == null) {
            List<DriverPositionModel> models = new ArrayList<DriverPositionModel>();
            models.add(model);
            String uploadContent = BestDataBaseHelper.getInstance().convertToString(models);
            Intent intent = new Intent();
            intent.putExtra("message", uploadContent);
            intent.setAction(BackService.MESSAGE_ACTION);
            BestApp.getInstance().sendBroadcast(intent);
        }
    }

    public void setLastKnowLocation(double lng, double lat, long timeStamp) {
        lastKnowLocation.mLng = lng;
        lastKnowLocation.mLat = lat;
        lastKnowLocation.mTimeStamp = timeStamp;
    }

    public LastKnowLocation getLastKnowLocation() {
        return lastKnowLocation;
    }

    private void updateByTimer() {
        if(!LocationManager.getInstance().isStarted()) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    LocationManager.getInstance().stopLocService();
                    LocationManager.getInstance().startLocService();
                }
            }, 5000);
        }
        startTimer(60000);
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    private void startTimer(int delay) {
        stopTimer();
        mTimer = new Timer("DISPLAY_TIME");
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                updateByTimer();
            }
        };
        mTimer.schedule(mTimerTask, delay);
    }

    private void getVersionRequest() {
        ApiObjectRequest<AppVersionInfo> request = RequestFactory.createGetVersionRequest(AppConfig.APP_VERSION, false, "Android");
        request.setListener(new ApiRequest.ApiRequestListener<AppVersionInfo>() {
            @Override
            public void onRequestSuccess(AppVersionInfo response) {
                UpgradeManager.getInstance(BestApp.getInstance()).checkAndNotify(BestApp.getInstance());
            }

            @Override
            public void onRequestError(BestError error) {

            }
        });
        AppProxyFactory.getProxy().getNetworkManager().enqueueRequest(request);
    }

    public String getPosition() {
        String position = "0,0";
        if(System.currentTimeMillis() - lastKnowLocation.mTimeStamp < 60000) {
            position = (new StringBuilder().append(lastKnowLocation.mLng).append(",").append(lastKnowLocation.mLat)).toString();
        }
        return position;
    }


}
